<template>
  <!-- 群发 -->
  <Top-Page class="mass-texting">
    <NavBar title="群发" :leftText="'取消'" @click-left="navBack" />

    <view class="mes-box">
      <view class="title">您将发送消息给{{ query.userNames.split(',').length }}个朋友:</view>
      <view class="content text-one">{{ query.userNames }}</view>
    </view>

    <view id="im-input">
      <imInput
        @send="sendMessage"
        :focusRev="false"
        :boxStatus="boxStatus"
        :contact="contact"
        :query="query"
        :type="'massTexting'"
        ref="imInput"
      ></imInput>
    </view>

    <Popup v-model:show="show" position="bottom" closeable round class="more-popup">
      <template v-if="pickerShow">
        <!-- 日期选择器 -->
        <picker-view
          ref="pickerView"
          class="uni-picker-view"
          indicator-style="height: 50px;"
          style="width: 100%; height: 300px"
          :value="pickerValue"
          @change="onTimeChange"
        >
          <!-- 年选择器 -->
          <picker-view-column>
            <view v-for="(year, index) in years" :key="index" class="picker-content">{{ year }}年</view>
          </picker-view-column>
          <!-- 月选择器 -->
          <picker-view-column>
            <view v-for="(month, index) in months" :key="index" class="picker-content">{{ month }}月</view>
          </picker-view-column>
          <!-- 日选择器 -->
          <picker-view-column>
            <view v-for="(day, index) in days" :key="index" class="picker-content">{{ day }}日</view>
          </picker-view-column>
          <!-- 时选择器 -->
          <picker-view-column>
            <view v-for="(hour, index) in hours" :key="index" class="picker-content">{{ hour }}时</view>
          </picker-view-column>
          <!-- 分选择器 -->
          <picker-view-column>
            <view v-for="(minute, index) in minutes" :key="index" class="picker-content">{{ minute }}分</view>
          </picker-view-column>
        </picker-view>

        <view class="btns">
          <view class="btn btn-1" @click="pickerShow = !pickerShow">取消</view>
          <view class="btn btn-2" @click="send(1)">定时发送</view>
        </view>
      </template>
      <template v-else>
        <view class="more-popup-title">选择发送方式</view>

        <view class="">分别发给{{ query.userNames.split(',').length }}个朋友</view>

        <view class="more-popup-content">
          <view class="text-one">{{ query.userNames }}</view>
        </view>

        <view class="btns">
          <view class="btn btn-1" @click="pickerShow = !pickerShow">定时发送</view>
          <view class="btn btn-2" @click="send(0)">立即发送</view>
        </view>
      </template>
    </Popup>
  </Top-Page>
</template>

<script>
import NavBar from '@/components/NavBar/NavBar.vue';
import Popup from '@/components/Popup/Popup.vue';
import { navBack } from '@/utils/utils.js';
import imInput from '@/components/message/im-input.vue';
import { useloginStore } from '@/store/login';
import pinia from '@/store/index';
const userStore = useloginStore(pinia);
export default {
  data() {
    return {
      navBack: navBack,
      // 当前时间
      currentTime: new Date(),
      // 日期选择范围
      years: [],
      months: [],
      days: [],
      hours: [],
      minutes: [],
      // picker-view 的默认选中项
      pickerValue: [],
      TimedTime: '', //定时时间
      //
      data: {},
      show: false,
      pickerShow: false, //定时任务
      query: {},
      contact: {},
      boxStatus: 0,
      user: userStore.userInfo
    };
  },
  components: { NavBar, imInput, Popup },
  created() {
    this.initTimeData();
  },
  onLoad(o) {
    Object.assign(this.query, o);
    if (this.query.userNames) {
      this.query.userNames = decodeURIComponent(this.query.userNames);
    }
  },
  watch: {
    show(s) {
      !s && (this.pickerShow = false);
    }
  },
  methods: {
    // 初始化时间数据
    initTimeData() {
      const currentYear = this.currentTime.getFullYear();
      const currentMonth = this.currentTime.getMonth() + 1; // 月份从0开始，所以要+1
      const currentDate = this.currentTime.getDate();
      const currentHour = this.currentTime.getHours();
      const currentMinute = this.currentTime.getMinutes();

      const maxDate = new Date();
      maxDate.setDate(currentDate + 7); // 设置最大日期为7天后

      // 生成年份数组
      this.years = [currentYear, maxDate.getFullYear()];
      // 生成月份数组
      this.months = this.generateArray(1, 12);
      // 生成日期数组
      this.days = this.generateDays(currentYear, currentMonth);
      // 生成小时数组
      this.hours = this.generateArray(0, 23);
      // 生成分钟数组
      this.minutes = this.generateArray(0, 59);

      // 初始化 picker-view 选中项
      this.pickerValue = [
        this.years.indexOf(currentYear),
        this.months.indexOf(currentMonth),
        this.days.indexOf(currentDate),
        this.hours.indexOf(currentHour),
        this.minutes.indexOf(currentMinute)
      ];
    },
    // 生成一个从 start 到 end 的数组
    generateArray(start, end) {
      const arr = [];
      for (let i = start; i <= end; i++) {
        arr.push(i);
      }
      return arr;
    },
    // 生成日期数组
    generateDays(year, month) {
      const daysInMonth = new Date(year, month, 0).getDate();
      return this.generateArray(1, daysInMonth);
    },
    // 获取指定月份的最大天数
    getMaxDays(year, month, maxDate) {
      const daysInMonth = new Date(year, month, 0).getDate();
      return month === maxDate.getMonth() + 1 ? maxDate.getDate() : daysInMonth;
    },
    // 时间改变时触发的事件
    onTimeChange(e) {
      const val = e.detail.value;
      this.pickerValue = val; // 更新 pickerValue 为当前选择的值
    },
    // 输出当前选择的时间
    printSelectedTime() {
      const selectedYear = this.years[this.pickerValue[0]];
      const selectedMonth = this.months[this.pickerValue[1]];
      const selectedDay = this.days[this.pickerValue[2]];
      const selectedHour = this.hours[this.pickerValue[3]];
      const selectedMinute = this.minutes[this.pickerValue[4]];

      const selectedTime = new Date(selectedYear, selectedMonth - 1, selectedDay, selectedHour, selectedMinute);

      // 获取本地时间字符串
      let formattedTime = selectedTime.toLocaleString('zh-CN', {
        hour12: false
      });

      // 替换斜杠为连字符
      formattedTime = formattedTime.replace(/\//g, '-');

      // 判断选中的时间是否超过7天范围;
      const maxDate = new Date(this.currentTime);
      maxDate.setDate(this.currentTime.getDate() + 7);

      if (selectedTime > maxDate || selectedTime < this.currentTime) {
        this.resetToCurrentTime();
        //定时时间
        this.TimedTime = '';
      } else {
        //定时时间
        this.TimedTime = formattedTime;
      }
    },
    // 重置为当前时间
    resetToCurrentTime() {
      console.log('重置为当前时间');
      uni.showToast({
        title: '有且只能选择此后七天内的时间段',
        icon: 'none'
      });

      this.initTimeData();
    },
    // 发送消息
    async sendMessage(message, file, isSecret) {
      uni.showToast({
        title: '上传中...',
        icon: 'loading',
        mask: true,
        duration: 999999
      });

      var fileTypes = ['image', 'file', 'video', 'voice'];
      let res = {};

      if (fileTypes.includes(message.type)) {
        message['greeting'] = 1;
        if (message.fileSize > 10240000) {
          return uni.showToast({
            title: '文件大小不能超过10M',
            icon: 'error'
          });
        }

        try {
          // 使用 await 等待上传结果
          const uploadRes = await uni.uploadFile({
            url: this.$api.msgApi.uploadUrl,
            filePath: message.content,
            name: 'file',
            header: {
              Authorization: uni.getStorageSync('authToken')
            },
            formData: {
              message: JSON.stringify(message)
            }
          });
          let parsedRes = JSON.parse(uploadRes.data);
          if (parsedRes.code === 0) {
            res = parsedRes.data;
          } else {
            throw new Error('上传失败');
          }
        } catch (error) {
          console.error('文件上传出错:', error);
          return;
        }
      }

      const user_id = this.query.userIds?.split(',') ?? [];
      const label_id = this.query.label?.split(',') ?? [];
      const group_id = this.query.group?.split(',') ?? [];
      const sex_id = this.query.sex?.split(',') ?? [];

      this.data = {
        type: message.type,
        content: message.content,
        to_user: {
          all: 0,
          user_id: user_id,
          label_id: label_id,
          group_id: group_id,
          sex_id: sex_id
        },
        send_time: ''
      };

      Object.assign(this.data, res);

      if (this.query.id) {
        this.data['greeting_id'] = this.query.id;
      }

      uni.hideToast();
      this.show = !this.show;
    },
    //发送
    send(type) {
      if (type === 1) {
        this.printSelectedTime();
        Object.assign(this.data, { send_time: this.TimedTime });
      }

      this.$api.msgApi.greetingAdd(this.data).then((res) => {
        uni.hideToast();
        if (res.code == 0) {
          this.show = false;

          uni.redirectTo({
            url: '/pages/greetings/greetings/greetings'
          });
        }
      });
    },
    getFormattedTimestamp() {
      const now = new Date();

      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
      const day = String(now.getDate()).padStart(2, '0');

      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    onClickLeft() {
      console.log('onClickLeft');
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
